package com.youtills.view;

import com.youtills.core.lang.StringUtil;
import com.youtills.resource.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * TODO - !!!doc me!!!
 *
 * @author ravi.chiluveru
 * @since 23.0 (7/19/14)
 */
public class RequestDispatcher {

    public static void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        final String path = request.getServletPath();
        List<String> paths = StringUtil.parseTokens(path, StringUtil.DOT);
        final String resource = paths.size() > 0 ? paths.get(0) : null;
        final String extension = paths.size() > 1 ? paths.get(1) : null;

        final HttpResourceController controller = getResourceController(resource, extension, request, response);

        final HttpResponseWriter writer = getResponseWriter(controller, extension);

        writer.writeResponse();

    }

    private static HttpResourceController getResourceController(final String resource, final String responseType, final HttpServletRequest req, final HttpServletResponse res) {

        if(ResourceController.EDIT_CONTROLLER.equals(resource)) {
            return new HttpEditResourceController(req, res);
        } else if(ResourceController.VIEW_CONTROLLER.equals(resource)) {
            return new HttpEditResourceController(req, res);
        } else if(ResourceController.DELETE_CONTROLLER.equals(resource)) {
            return new HttpEditResourceController(req, res);
        } else {
            return new HttpEditResourceController(req, res);
        }

    }

    private static HttpResponseWriter getResponseWriter(final HttpResourceController controller, final String responseType){
        //TODO - check for response type and create appropriate writer.
        if("json".equals(responseType)) {
            return new HttpJsonResponseWriter(controller);
        } else {
            return new HtmlResponseWriter(controller);
        }
    }
}
